
<template>
  <main class="page-main">
    <div class="padding-20">

      <a-row class="margin-top-10">
        <a-col :span="4">
          <div class="padding-10">
            <div class="text-right margin-bottom-20">
              <a-button type="primary" @click="handleAddMode">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加分组
              </a-button>
            </div>
            <a-menu
                mode="inline"
                :items="groupTree"
                @click="handleMenuClick"
            ></a-menu>
          </div>
        </a-col>
        <a-col :span="20" class="left-line">
          <div>
            <!-- 操作按钮 -->
            <div class="text-right margin-bottom-20">
              <a-button type="primary"  @click="handleAddMode('Menu')">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加菜单
              </a-button>
              <a-button class="margin-left-20" type="dashed" @click="handleExport">
                <template #icon>
                  <DownloadOutlined />
                </template>
                导出
              </a-button>
            </div>

            <a-table
                bordered
                :columns="columns"
                :data-source="pageData"
                :pagination="false"
                rowKey="id"
                class="ant-table-striped"
                :row-class-name="(_record, index) => (_record.type==='Button' ? 'table-striped' : null)"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'actionColumn'">
                  <a-flex class="width" justify="space-around">
                    <a-tooltip title="添加按钮">
                      <a-button type="text" size="small" class="button-create"
                                v-if="record.type==='Menu'" @click="handleAddMode('Button',record.id)">
                        <template #icon>
                          <PlusOutlined />
                        </template>
                        添加按钮
                      </a-button>
                    </a-tooltip>
                    <a-tooltip title="修改" >
                      <a-button type="text" size="small" class="button-edit" @click="handleEditMode(record.type, record.id)">
                        <template #icon>
                          <FormOutlined />
                        </template>
                        修改
                      </a-button>
                    </a-tooltip>
                    <a-tooltip title="删除" >
                      <a-button type="text" size="small" class="button-delete" @click="handleDeleteMode(record.id, 'Menu')">
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                        删除
                      </a-button>
                    </a-tooltip>
                  </a-flex>
                </template>
                <template v-if="column.key === 'type'">
                  {{record.type === 'Menu' ? '菜单' : '按钮'}}
                </template>
                <template v-if="column.key === 'iconName'">
                  <Icon v-if="record.iconName" :icon-name="record.iconName" />
                </template>
                <template class="width" v-if="column.key === 'apiNames' && record.apiNames">
                  <a-popover title="绑定的API" v-if="record.apiNames.length > 1">
                    <template #content>
                      <div v-for="item in record.apiNames" :key="item">
                        <a-tag class="margin-5">{{ item }}</a-tag>
                      </div>
                    </template>
                    <a-button>{{record.apiNames[0] + '...'}}</a-button>
                  </a-popover>
                  <div v-else>{{record.apiNames[0]}}</div>
                  <!--                  <a-tag class="margin-5" v-for="item in record.apiNames" :key="item"-->
                  <!--                         :color="record.type==='Menu' ? 'blue' : 'green'">{{ item }}</a-tag>-->
                  <!--                  <a-tag class="margin-5" v-for="item in record.apiNames" :key="item"-->
                  <!--                        >{{ item }}</a-tag>-->
                </template>
              </template>
            </a-table>
          </div>

        </a-col>
      </a-row>
    </div>

    <!-- 新增、编辑的表单 -->
    <a-drawer
        v-model:open="mode.edit"
        :title="(currentId ? '修改' : '添加')+(currentType === 'Menu' ? '菜单' : '按钮')"
        size="large"
    >
      <Form
          :key="new Date().getTime()"
          :dataId="currentId"
          :type="currentType"
          :menuId="currentParentId"
          @close="handleCancel"
          @successed="handleQueryList"
      />
    </a-drawer>

    <!-- 删除 -->
    <a-modal v-model:open="mode.delete" title="确定删除">
      <span>确定删除{{ currentType === "Menu" ? "菜单" : "按钮" }}吗？删除后数据不可恢复</span>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" danger @click="handleDelete">删除</a-button>
      </template>
    </a-modal>
  </main>
</template>

<script setup lang="ts">
import {ref, onMounted, h} from 'vue'
import * as apiUtil from "@/api/ApiUtils"
import * as api from "@/api/AuthResourceApi"
import Form from "./form.vue"
import { notification } from "ant-design-vue"
import Icon from "@/components/Icon.vue"
import {
  DeleteOutlined,
  DownloadOutlined,
  FormOutlined,
  PlusOutlined
} from "@ant-design/icons-vue"
import {Resource,ResourceQuery} from "@/api/AuthResourceApi";

import {getIcon} from "@/utils/IconUtils";
import type { MenuProps, ItemType } from 'ant-design-vue';

// 响应式状态
const pageData = ref<Resource[]>([])
const currentId = ref<number | null>(null)
const currentType = ref<string>('')
const currentParentId = ref<number | null>(null)
const groupTree = ref([]);

const queryData = ref<ResourceQuery>(new ResourceQuery())

const mode = ref({
  edit: false,
  delete: false,
  group:false
})

const columns = [
  { title: '图标', dataIndex: 'iconName', key: 'iconName' ,align:"center"},
  { title: '类型', dataIndex: 'type', key: 'type',align:"center" },
  { title: '名称', dataIndex: 'name', key: 'name' ,align:"center"},
  // { title: '标识符', dataIndex: 'webPath', key: 'webPath' },
  { title: 'API', dataIndex: 'apiNames', key: 'apiNames',width: 300},
  // { title: '排序', dataIndex: 'sort', key: 'sort' },
  { title: '操作', key: 'actionColumn',align:"center"}
]

// 生命周期钩子
onMounted(() => {
  api.menuGroupList().then((res)=>{
    if(apiUtil.isSuccessed(res)){
      for (let item of res.data) {
        item.id = item.id + "";
        item.label = item.name;
        item.key = item.id;
        item.icon = h(getIcon(item.iconName));
      }
      groupTree.value = res.data;
    }
  })
  handleQueryList();
})

// 业务方法
const handleQueryList = async () => {
  try {
    const res = await api.list(queryData.value)
    if (apiUtil.isSuccessed(res)) {
      pageData.value = res.data;
    }
  } catch (error) {
    notification.error({
      message: "查询失败",
      description: error.message
    })
  }
}

const handleDelete = async () => {
  try {
    const res = await api.deleteById(currentId.value!)
    if (apiUtil.isSuccessed(res)) {
      notification.success({
        message: "删除成功",
        description: "已删除"
      })
      mode.value.delete = false
      await handleQueryList()
    }
  } catch (error) {
    notification.error({
      message: "删除失败",
      description: error.message
    })
  }
}

const handleAddMode = (type?: string, menuId: number | null = null) => {
  currentId.value = null
  currentParentId.value = menuId
  currentType.value = type || ''
  mode.value.edit = true
}

const handleEditMode = (type: string, id: number) => {
  currentId.value = id
  currentType.value = type
  mode.value.edit = true
}

const handleDeleteMode = (id: number, type: string) => {
  currentId.value = id
  currentType.value = type
  mode.value.delete = true
}

const handleCancel = () => {
  mode.value.edit = false
  mode.value.delete = false
  currentId.value = null
  currentType.value = ''
  currentParentId.value = null
}

const handleChange = (current: number, size: number) => {
  queryData.value.size = size;
  queryData.value.current = current
  handleQueryList()
}

const handleMenuClick: MenuProps['onClick'] = e => {
  console.log('click', e.key);
  queryData.value.groupId = e.key;
  handleQueryList();
};

const handleExport = () => {
  api.exportList(queryData.value)
}
</script>


<style scoped>
/* 保持原有样式不变 */
.ant-table-striped :deep(.table-striped) td {
  background-color: #f5f5f5;
}
</style>
